package edu.whut.mall.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageHelper;
import edu.whut.mall.admin.domain.GroupBuyRuleParams;
import edu.whut.mall.admin.domain.ProductImageParams;
import edu.whut.mall.admin.domain.ProductParams;
import edu.whut.mall.admin.domain.ProductSearchParams;
import edu.whut.mall.admin.enums.ProductStatusEnum;
import edu.whut.mall.admin.enums.ProductVerifyStatusEnum;
import edu.whut.mall.admin.enums.SysStatusEnum;
import edu.whut.mall.admin.enums.UserRoleEnum;
import edu.whut.mall.admin.mapper.ProductCustomMapper;
import edu.whut.mall.admin.mapper.ProductImageCustomMapper;
import edu.whut.mall.admin.service.IProductService;
import edu.whut.mall.admin.shiro.util.ShiroUtil;
import edu.whut.mall.admin.vo.ProductVo;
import edu.whut.mall.common.api.CommonPage;
import edu.whut.mall.mapper.GroupBuyRuleMapper;
import edu.whut.mall.mapper.ProductImageMapper;
import edu.whut.mall.mapper.ProductMapper;
import edu.whut.mall.model.GroupBuyRule;
import edu.whut.mall.model.Product;
import edu.whut.mall.model.ProductExample;
import edu.whut.mall.model.ProductImageExample;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;

/**
 * @program: d9lab-mall
 * @description: 商品服务实现类
 * @author: Wayne
 * @create: 2020-05-05 11:42
 **/
@Service
@RequiredArgsConstructor
@Slf4j
public class ProductServiceImpl implements IProductService {

    private final ProductMapper productMapper;

    private final ProductCustomMapper productCustomMapper;

    private final GroupBuyRuleMapper groupBuyRuleMapper;

    private final ProductImageMapper productImageMapper;

    private final ProductImageCustomMapper productImageCustomMapper;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer insertOneProduct(ProductParams productParams) {
        Product product = new Product();
        BeanUtils.copyProperties(productParams,product);
        product.setVerifyStatus(ProductVerifyStatusEnum.PRODUCT_IN_REVIEW.getCode());
        product.setStatus(ProductStatusEnum.PRODUCT_ON_SALE.getCode());
        product.setMerchantId(ShiroUtil.getMerchantId());
        productMapper.insertSelective(product);
        return batchInsertProductImageList(productParams.getProductImages(), product.getId());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer updateOneProduct(Long productId, ProductParams productParams) {
        ProductImageExample productImageExample = new ProductImageExample();
        productImageExample.createCriteria().andProductIdEqualTo(productId);
        productImageMapper.deleteByExample(productImageExample);
        Product product = new Product();
        BeanUtils.copyProperties(productParams, product);
        product.setId(productId);
        product.setUpdateTime(new Date());
        productMapper.updateByPrimaryKeySelective(product);
        return batchInsertProductImageList(productParams.getProductImages(), product.getId());
    }

    @Override
    public Integer setProductStatus(Long productId, Integer status) {
        Product product = new Product();
        product.setId(productId);
        product.setStatus(status);
        return productMapper.updateByPrimaryKeySelective(product);
    }

    @Override
    public Integer setProductVerifyStatus(Long productId, Integer status) {
        Product product = new Product();
        product.setId(productId);
        product.setVerifyStatus(status);
        return productMapper.updateByPrimaryKeySelective(product);
    }

    @Override
    public ProductVo getProductDetailVoByProductId(Long productId) {
        return productCustomMapper.getProductDetailVoByProductId(productId);
    }

    @Override
    public CommonPage<ProductVo> listProductVosByCategoryId(Long categoryId, Integer pageNum, Integer size) {
        PageHelper.startPage(pageNum, size);
        List<ProductVo> productVoList = productCustomMapper.listProductVosByCategoryId(categoryId);
        return CommonPage.restPage(productVoList);
    }

    @Override
    public CommonPage<ProductVo> listMerchantOwnProductVos(Integer pageNum, Integer size) {
        PageHelper.startPage(pageNum, size);
        List<ProductVo> productVoList = productCustomMapper.listProductVos(ShiroUtil.getMerchantId());
        return CommonPage.restPage(productVoList);
    }

    @Override
    public CommonPage<ProductVo> listProductVosByCondition(ProductSearchParams productSearchParams, Integer pageNum, Integer size) {
        PageHelper.startPage(pageNum, size);
        if (ShiroUtil.getAdminType().equals(UserRoleEnum.MERCHANT_ADMIN.getCode())) {
            productSearchParams.setMerchantId(ShiroUtil.getMerchantId());
        }
        List<ProductVo> productVoList = productCustomMapper.listProductVosByCondition(productSearchParams);
        return CommonPage.restPage(productVoList);
    }

    @Override
    public Integer deleteOneProduct(Long productId) {
        Product product = new Product();
        product.setId(productId);
        product.setIsDeleted(1);
        return productMapper.updateByPrimaryKeySelective(product);
    }

    @Override
    public Integer deleteProductByMerchantId(Long merchantId) {
        Product product = new Product();
        product.setIsDeleted(1);
        ProductExample productExample = new ProductExample();
        productExample.createCriteria().andMerchantIdEqualTo(merchantId);
        return productMapper.updateByExampleSelective(product, productExample);
    }

    @Override
    public Integer assignGroupBuyRuleToProduct(GroupBuyRuleParams groupBuyRuleParams) {
        Product product = productMapper.selectByPrimaryKey(groupBuyRuleParams.getProductId());
        BigDecimal discountRate = groupBuyRuleParams.getGroupBuyPrice().divide(product.getCurrentPrice(), 2, RoundingMode.HALF_UP);
        GroupBuyRule groupBuyRule = new GroupBuyRule();
        BeanUtil.copyProperties(groupBuyRuleParams, groupBuyRule);
        groupBuyRule.setDiscountRate(discountRate);
        groupBuyRule.setSuccessGroupNumber(0);
        groupBuyRule.setStatus(SysStatusEnum.AVAILABLE.getCode());
        return groupBuyRuleMapper.insertSelective(groupBuyRule);
    }

    /**
     * 批量插入商品图片
     * @param productImageList 商品图片类的参数
     * @param productId 商品id
     * @return 插入了多少条
     */
    private Integer batchInsertProductImageList(List<ProductImageParams> productImageList, Long productId) {
        if (CollectionUtils.isNotEmpty(productImageList)) {
            for (int i = 0; i < productImageList.size(); i++) {
                if (i == 0) {
                    productImageList.get(i).setIsMain(1);
                } else {
                    productImageList.get(i).setIsMain(0);
                }
                productImageList.get(i).setProductId(productId);
            }
            return productImageCustomMapper.batchInsert(productImageList);
        }
        return 0;
    }
}
